﻿var zombies = zombies || {};

zombies.ListMember = function () {
    var self = this;
    self.Members = ko.observableArray();
    self.SearchString = ko.observable("");
    self.CurrentPage = ko.observable(1);
    self.IsPrevious = ko.observable(false);
    self.IsNext = ko.observable(false);
    self.Loaded = ko.observable(false);

    self.SendMsg = function () {
        self.CurrentPage(1);
        load(self.CurrentPage(), self.SearchString());
        $.replaceUrl(self.CurrentPage(), self.SearchString());
    };

    self.EnterSendMsg = function (data, event) {
        try {
            if (event.which === 13) {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
                return false;
            }
            return true;
        }
        catch (e)
        { }
    };

    self.MemId = ko.observable();
    self.UserName = ko.observable();
    self.FirstName = ko.observable();
    self.LastName = ko.observable();
    self.Gender = ko.observable("Male");
    self.Email = ko.observable();
    self.Level = ko.observable();
    self.Point = ko.observable();
    self.CMND = ko.observable();

    self.Gender.ForCheck = ko.computed({
        read: function () {
            return self.Gender().toString();
        },
        write: function (newValue) {
            self.Gender(newValue);
        },
        owner: self
    });

    self.doView = function (item) {
        self.MemId(item.MemId);
        self.UserName(item.UserName);
        self.FirstName(item.FirstName);
        self.LastName(item.LastName);
        self.Gender(item.Gender);
        self.Email(item.Email);
        self.CMND(item.CMND);
        self.Point(item.Point);
        self.Level(item.Level);
    };

    self.doEdit = function (formElement) {
        var member = ko.utils.arrayFirst(self.Members(), function (item) {
            return item.MemId === self.MemId();
        });

        var dataToEdit = {
            MemId: self.MemId,
            UserName: self.UserName,
            FirstName: self.FirstName,
            LastName: self.LastName,
            Gender: self.Gender,
            Email: self.Email,
            CMND: self.CMND,
            Point: self.Point,
            Level: self.Level
        };

        if ($(formElement).valid()) {
            $.ajax({
                type: "POST",
                url: "/api/AdminMember/EditMember",
                data: ko.toJSON(dataToEdit),
                contentType: "application/json",
                dataType: 'json'
            }).done(function () {
                self.Members.replace(member, {
                    MemId: self.MemId(),
                    UserName: self.UserName(),
                    FirstName: self.FirstName(),
                    LastName: self.LastName(),
                    Gender: self.Gender(),
                    Email: self.Email(),
                    Level: self.Level(),
                    Point: self.Point(),
                    CMND: self.CMND()
                });
                $('#editmem-div').removeClass('active in');
                $('#listmem-div').addClass('active in');
                toastr.success('Cập Nhật Thông Tin Tài Khoản Người Dùng Thành Công!');
            }).fail(function (request) {
                var msg = request.responseText.substring(12);
                msg = msg.substring(0, msg.length - 2);
                toastr.error(msg);
            });
        }
    };

    self.doDelete = function (item) {
        $.confirm({
            text: "Bạn Có Chắc Chắn Muốn Xóa Tài Khoản Thành Viên <strong style='color: red'>" + item.UserName + " </strong> Không?</br>Thao Tác Này Không Thể Khôi Phục.",
            title: "<strong>Xác Nhận Xóa Tài Khoản</strong>",
            confirm: function (button) {
                $.ajax({
                    type: "DELETE",
                    url: "/api/AdminMember/DeleteMember/" + item.MemId,
                    success: function (data) {
                        self.Members.remove(item);
                        if (self.CurrentPage() > 1 && self.Members().length == 0) {
                            self.doPrevious();
                        }
                        toastr.success("Xóa Tài Khoản Thành Viên Thành Công!");
                    },
                    error: function (error) {
                        toastr.error("Xóa Tài Khoản Thành Viên Thất Bại!");
                    }
                });
            },
            confirmButton: "Xác Nhận Xóa",
            cancelButton: "Thoát"
        });
    };

    self.doNext = function () {
        if (self.IsNext()) {
            var page = self.CurrentPage();
            page++;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#listmem_div'), -50);
        }
    };

    self.doPrevious = function () {
        if (self.IsPrevious()) {
            var page = self.CurrentPage() - 1;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#listmem_div'), -50);
        }
    };
}

var load = function (id, searchString) {
    viewModel.Loaded(false);
    viewModel.Members.removeAll();

    $.ajax({
        url: '/api/AdminMember/GetMembers/' + id,
        type: 'GET',
        data: { value: searchString },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items.length === 11) {
            items.pop();
            viewModel.IsNext(true);
        } else {
            viewModel.IsNext(false);
        }
        $.each(items, function (idx, item) {
            viewModel.Members.push(new zombies.Member(item));
        });
        viewModel.Loaded(true);
    }).error(function () {
        toastr.error('error');
    })
};

var pageUrl = $.getUrlVars("page");
var searchStringUrl = $.getUrlVars("searchString");
var viewModel;
$(document).ready(function () {

    viewModel = new zombies.ListMember();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));
    
    if (typeof pageUrl === 'undefined' || !isFinite(String(pageUrl))) {
        viewModel.CurrentPage(1);
    } else {
        viewModel.CurrentPage(pageUrl);
    }
    if (typeof searchStringUrl === 'undefined') {
        viewModel.SearchString("");
    } else {
        viewModel.SearchString(searchStringUrl);
    }
    if (pageUrl > 1) viewModel.IsPrevious(true);
    
    load(viewModel.CurrentPage(), viewModel.SearchString());
});